package com.weigecoder.warehouse.handler;

import com.weigecoder.warehouse.entity.Result;
import com.weigecoder.warehouse.exception.BusinessException;
import com.weigecoder.warehouse.exception.SysException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义的公共异常处理器
 *      1.声明异常处理器
 *      2.对异常统一处理
 */
@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Result error(HttpServletRequest request, HttpServletResponse response, Exception e) {
        e.printStackTrace();
        if(e.getClass() == BusinessException.class) {
            //类型转型
            BusinessException businessException = (BusinessException) e;
            return Result.err(Result.CODE_ERR_BUSINESS,"操作失败，请重试！");
        }else if(e.getClass() == SysException.class){
            SysException sysException = (SysException) e;
            return Result.err(Result.CODE_ERR_SYS,"服务器繁忙，请稍后重试！");
        }
        return null;
    }

}
